package cn.lj.ykt.service.impl;


import cn.lj.ykt.businessconstant.Constant;
import cn.lj.ykt.dto.RedisPhoneCode;
import cn.lj.ykt.exception.GlobleBusinessException;
import cn.lj.ykt.service.VerifyCodeService;
import cn.lj.ykt.util.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void sendSmsCode(String phone) {

        //1.校验
        if (phone == null){
            throw new GlobleBusinessException("手机号码不能为空");
        }

        String key = Constant.PHONE_REGISTER + phone;
        RedisPhoneCode obj = (RedisPhoneCode) redisTemplate.opsForValue().get(key);
        //2.从redis中获取验证码，如果有，且存在时间1分钟内返回，请勿从新发送
        if(obj != null){
            long curr = System.currentTimeMillis();
            if(curr - obj.getDate()  < 60 * 1000){
                throw new GlobleBusinessException("请勿重复发送验证码");
            }
        }
        //4.如果redis里面也没有数据，需要先存redis然后返回数据
//      String code = VerifyCodeUtils.generateVerifyCode(4);
        String code = StrUtils.getRandomString(4);
        long date = System.currentTimeMillis();
        RedisPhoneCode redisPhoneCode = new RedisPhoneCode(code, date);
        log.info("验证码为：=========================>{}",code);
        redisTemplate.opsForValue().set(key, redisPhoneCode, 5, TimeUnit.MINUTES);
//        SendSms.sendSms(phone,code);
    }
}
